import http from "@/api/request";
import { LOGIN_URL } from "@/@CORE/app-config/config";
import router from "@/router";
import { GlobalStore } from "@/stores";

export default () => {
	const globalStore = GlobalStore();

	/**
	 * 登录
	 * @param datas
	 * @returns {Promise<unknown>}
	 */
	async function login(datas) {
		return new Promise((resolve, reject) => {
			http
				.post("backend/site/login", datas, { config: { noLoading: false, sendOriginalData: false } })
				.then(res => {
					globalStore.SET_TOKEN(res.data.token);
					resolve(res);
				})
				.catch(err => {
					reject(err);
				});
		});
	}

	/**
	 * 注册用户/添加用户
	 * @param datas
	 * @returns {Promise<*>}
	 */
	async function register(datas) {
		return await http.post("admin/user/register", datas);
	}

	/**
	 * 获取当前账号信息
	 * @returns {Promise<*>}
	 */
	async function getUserInfo() {
		return await http.get("admin/user/get-info");
	}

	/**
	 * 获取当前角色拥有路由
	 * @returns {Promise<*>}
	 */
	async function getRouters() {
		return await http.get("backend/user-menu/route");
	}
	/**
	 * 获取当前角色拥有路由
	 * @returns {Promise<*>}
	 */
	async function getRoleSidebar() {
		return await http.get("backend/user-menu/menu");
	}

	async function getRoleButton() {
		return await http.post("admin/user/get-button");
	}

	async function logout() {
		globalStore.SET_TOKEN("");
		router.resetRouter();
		await router.push(LOGIN_URL);
		// return await http.get("admin/user/logout");
	}

	return {
		login,
		register,
		getUserInfo,
		getRouters,
		getRoleSidebar,
		getRoleButton,
		logout
	};
};
